# -*- coding:utf-8 -*-

import logging
import time
import random
from apscheduler.schedulers.blocking import BlockingScheduler
from apscheduler.events import EVENT_JOB_EXECUTED, EVENT_JOB_ERROR
from api.api import get_markets

logging.basicConfig()
logging.getLogger('apscheduler').setLevel(logging.DEBUG)


def my_listener(event):
    if event.exception:
        print('[scheduler] 程序执行成功   The job crashed :(')
    else:
        print('[scheduler] 程序执行失败  The job worked :)')


def cron_1():
    interval = 10
    while True:
        get_markets()
        time.sleep(random.randrange(interval))


def cron_2():
    interval = 60 * 60 * 2
    max_instances = 3
    trigger = 'interval'
    scheduler = BlockingScheduler()
    scheduler.add_job(get_markets, trigger, seconds=interval,
                      max_instances=max_instances)
    scheduler.add_listener(my_listener, EVENT_JOB_EXECUTED | EVENT_JOB_ERROR)
    try:
        scheduler.start()
    except (KeyboardInterrupt, SystemExit):
        pass


def main():
    cron_1()


if __name__ == "__main__":
    main()
